package com.yellowzp.demoapisql.apisql;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Component
public class SqlEncryptor {

    /**
     * 秘钥的byte字符串
     */
    private static final String KEY_STRING = "cWLF8AiBkhx7mG8nhyrY6A==";

    /**
     * 秘钥
     */
    private SecretKey key;

    private static final String ALGORITHM = "AES";

    public SqlEncryptor() {
        generateKeyFromKeyString(KEY_STRING);
    }

    public SqlEncryptor(String keyString) {
        generateKeyFromKeyString(keyString);
    }

    public void generateKeyFromKeyString(String keyString) {
        byte[] keyBytes = Base64.getDecoder().decode(keyString);
        this.key = new SecretKeySpec(keyBytes, ALGORITHM);
    }

    /**
     * 生成一个秘钥字符串
     * @param n 秘钥长度 单位byte 128 256 512等
     * @return
     * @throws Exception
     */
    public static String generateKeyString(int n) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(n);
        return Base64.getEncoder().encodeToString(keyGenerator.generateKey().getEncoded());
    }

    // 加密
    public String encrypt(String input) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherText = cipher.doFinal(input.getBytes());
        return Base64.getEncoder().encodeToString(cipherText);
    }

    // 解密
    public String decrypt(String cipherText) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedValue = Base64.getDecoder().decode(cipherText);
        byte[] decryptedValue = cipher.doFinal(decodedValue);
        return new String(decryptedValue);
    }

    public static void main(String[] args) throws Exception {
        String keyString = SqlEncryptor.generateKeyString(128);
        System.out.println(keyString);
        SqlEncryptor sqlEncryptor = new SqlEncryptor();
        sqlEncryptor.generateKeyFromKeyString(keyString);
        String sql = "select 1 from dual";
        String encrypt = sqlEncryptor.encrypt(sql);
        System.out.println(encrypt);
        System.out.println(sqlEncryptor.decrypt(encrypt));
        // vmrdddCHIkEm8tXchDOyNCQUHYq+5o1gcLpjYaNTUfk=
    }
}
